﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Threading;
using SvgViewer.Utilities;

namespace SvgViewer.Core;

internal static class ViewModelDesignHelper
{
    public static bool? IsInDesignModeOverride;
}

/// <summary>
/// ViewModel 基类
/// </summary>
public abstract class ViewModelBase : NotifyPropertyBase
{
    private static bool? isInDesignMode;

    /// <summary>
    /// 获取或设置 ViewModel 使用的视图服务
    /// </summary>
    public IViewService ViewService { get; set; }

    /// <summary>
    /// 是否设计模式
    /// </summary>
    public static bool IsInDesignMode {
        get {
            if (ViewModelDesignHelper.IsInDesignModeOverride != null)
            {
                return ViewModelDesignHelper.IsInDesignModeOverride.Value;
            }

            if (isInDesignMode == null)
            {
                var dependencyPropertyDescriptor =
                    DependencyPropertyDescriptor.FromProperty(DesignerProperties.IsInDesignModeProperty,
                        typeof(FrameworkElement));
                if (dependencyPropertyDescriptor == null)
                {
                    return false;
                }

                isInDesignMode = (bool)dependencyPropertyDescriptor.Metadata.DefaultValue;
            }

            return isInDesignMode.Value;
        }
    }

    /// <summary>
    /// 构造
    /// </summary>
    protected ViewModelBase()
    {
        ThemeManager.Instance.PropertyChanged += ThemePropertyChanged;
        if (IsInDesignMode)
        {
            Dispatcher.CurrentDispatcher.BeginInvoke(OnInitializeInDesignMode, Array.Empty<object>());
            return;
        }

        this.OnInitializeInRuntime();
    }

    /// <summary>
    /// 
    /// </summary>
    ~ViewModelBase()
    {
        ThemeManager.Instance.PropertyChanged -= ThemePropertyChanged;
    }

    private void ThemePropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        this.OnPropertyChanged(e.PropertyName);
    }

    /// <summary>
    /// 
    /// </summary>
    protected virtual void OnInitializeInRuntime() { }

    /// <summary>
    /// 
    /// </summary>
    protected virtual void OnInitializeInDesignMode() { }

    /// <summary>
    /// 获取或设置是否为深色模式
    /// </summary>
    public bool IsDark {
        get => ThemeManager.Instance.IsDark;
        set => ThemeManager.Instance.IsDark = value;
    }
}